package com.wkq.net

import com.google.gson.GsonBuilder
import com.wkq.net.gson.StringTypeAdapter
import com.wkq.net.interceptor.HttpHeadersInterceptor
import com.wkq.net.interceptor.LoggingInterceptor
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/6/20 16:26
 *
 *@Desc: 配置 请求的数据
 */
object HttpConfig {
    /**
     * 是否开启 Https 证书校验  携带域名和证书 唯一值的方式
     */
     fun getRetrofitInstance(isHttpsPing:Boolean=false): Retrofit {
        val bulid=GsonBuilder().setLenient()
        return Retrofit.Builder()
            .client(createOkHttpClient(isHttpsPing))
            .baseUrl(RetrofitNetConfig.getInstance().getNetBaseUrl()?:"")
            .addConverterFactory(
                GsonConverterFactory.create(
                    bulid.registerTypeAdapter(
                        String::class.java, StringTypeAdapter()
                    ).create()
                )
            )
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
            .build()

    }

    /**
    *创建 OkHttpClient
     */
     fun createOkHttpClient(isHttpsPing:Boolean=false): OkHttpClient {
        val builder = OkHttpClient.Builder()
            .writeTimeout(5, TimeUnit.SECONDS)
            .connectTimeout(5, TimeUnit.SECONDS)
            .addInterceptor(HttpHeadersInterceptor(RetrofitNetConfig.getInstance().getNetHeader()))

        if (RetrofitNetConfig.getInstance().isNetDebug() == true) {
            builder.addInterceptor(LoggingInterceptor())
        }
        if (isHttpsPing)
            builder.certificatePinner(
                CertificatePinner.Builder()
                    .add("dev.qiandurebo.com", "sha256/VG4SoOvnC2tQyqt7pPXJJAeX3W/m95U5henzHaAxzY0=")  // 备用证书
                    .add("api.qiandurebo.com", "sha256/w6R2zL/QxEm+JOjxEqNhh2wjyoPPUagFS0g7E7bQ9H0=")  // 主证书
                    .add("qiandurebo.com", "sha256/unGMP9eLHpiWqpTlIFsfd6U1nry89S66cJq8uVVismM=")
                    .build()
            )
        return builder.build()
    }
}